package org.shangrila.app;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.shangrila.app.sys.cfg.AppInitInfo;
import org.shangrila.app.sys.eo.SysDictitem;
import org.shangrila.bme.eo.BmeContProd;
import org.shangrila.bme.eo.BmeContPurch;
import org.shangrila.bme.eo.BmeMaterial;
import org.shangrila.bme.eo.BmeProdBom;
import org.shangrila.comm.dao.DbAccess;
import org.shangrila.comm.helper.DateHelper;
import org.shangrila.comm.helper.IDHelper;
import org.shangrila.wfm.core.WfmEngine;
import org.shangrila.wfm.core.WfmHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
public class Test {
	private static final Logger log = LoggerFactory.getLogger(Test.class);

	public static void main(String[] args) {
		
	    BigDecimal b = new BigDecimal(3);
	    String speci="500*300";
	    System.out.println(calc(b,speci));
    	

	    
		/*WfmEngine engine = WfmHelper.getEngine();
		
		List voListLog = engine.getWfmdao().findServiceLogByNoAndCreator("20180828","bme");
		System.out.println("voListLog="+voListLog.size());*/
		//onGenPurch();
		
		//AppInitInfo();
		//dataQuery();
		/*
		WfmEngine engine = new WfmEngine();
		String processName="wf_shd_test";
		WfmTask wfmTask = engine.startServiceWithTask(engine.getWfmdao().findProcessByName(processName).get(0), "Test", null);
		System.out.println("wfmTask="+wfmTask.getId());	
		engine.commitTask(wfmTask, "Test", null);
		*/
		System.exit(0);
	}
	public static BigDecimal calc(BigDecimal b,String speci){
		try {
	    	double q = b.doubleValue();
	    	int i = speci.indexOf("*");
	    	double d1=Integer.parseInt(speci.substring(0, i))/1000.00;
	    	double d2=Integer.parseInt(speci.substring(i+1))/1000.00;
	    	//double k=(double)Math.round(q/(d1*d2)*100)/100; //double保持2位小数
	    	return new BigDecimal(q/(d1*d2)).setScale(2, BigDecimal.ROUND_HALF_UP);//BigDecimal保持2位小数
    	}catch(Exception e) {
    		return new BigDecimal(0);
    	}
	}
	//生成采购清单
	public static void onGenPurch() {
		DbAccess db = new DbAccess();
		String operator="AAA";
		List<BmeContProd> vop = new ArrayList<BmeContProd>(); //合同产品
		List<BmeContPurch> voppm = new ArrayList<BmeContPurch>(); //采购清单
		String bmeContractId="20180828";

		//从BmeContProd表生成BmeContPurch数据：
		//如果不是BOM产品，则直接复制
		//如果是BOM产品，则需要分解BOM的物料清单进行复制，物料ID相同的则合并计算数量
		voppm = new ArrayList<BmeContPurch>();
		String sql = "select o from BmeContProd o where o.bmeContract.id=?1";
		vop =db.findBySql(sql,new Object[] {bmeContractId});		
		try {			
			List<BmeContProd> bom = new ArrayList<BmeContProd>(); 
			//把BOM自制类别的产品暂存起来，其他的直接插入采购清单
			for(BmeContProd bcp:vop) {
				if("2".equals(bcp.getBmeMaterial().getMsort())) {
					bom.add(bcp); 
				}
				else {
					BmeContPurch bcpurch  = new BmeContPurch();
					bcpurch.setId(IDHelper.genStrID(20));
					bcpurch.setBmeContract(bcp.getBmeContract());
					bcpurch.setContName(bcp.getBmeContract().getName());
					bcpurch.setBmeMaterial(bcp.getBmeMaterial());
					bcpurch.setContName(bcp.getContName());
					bcpurch.setSupplierId(bcp.getSupplierId());
					
					bcpurch.setPrice(bcp.getPrice());
					bcpurch.setQuantity(bcp.getQuantity());
					bcpurch.setAmount(bcp.getAmount());
					
					bcpurch.setRemarks(bcp.getRemarks());				
					bcpurch.setCreateTime(new Date());
					bcpurch.setOperator(operator);
					//bcpInsert.add(bcpurch);
					voppm.add(bcpurch);
				}
			}
			
			//找出BOM类别的物料清单，每个MID都进行数量和金额计算，生成一个BmeContPurch列表（BOM物料相关）
			sql = "select o from BmeProdBom o where o.pid=?1";
			List<BmeContPurch> bcplist = new ArrayList<BmeContPurch>(); 
			for(BmeContProd bcp:bom) {
				List<BmeProdBom> tmplist = db.findBySql(sql,new Object[] {bcp.getBmeMaterial().getId()});
				if(tmplist.size()>0) {
					for(BmeProdBom bo:tmplist) {  //处理数量:这个地方有坑，不能直接修改和使用bo，否则会把bo提交保存
						BmeContPurch bcpurch  = new BmeContPurch();
						bcpurch.setId(IDHelper.genStrID(20));
						bcpurch.setBmeContract(bcp.getBmeContract());
						BmeMaterial bm = new BmeMaterial();
						bm.setId(bo.getMid());
						bcpurch.setBmeMaterial(bm);
						bcpurch.setContName(bcp.getContName());
						bcpurch.setSupplierId(bcp.getSupplierId());
						bcpurch.setPrice(bo.getSalePrice());
						bcpurch.setQuantity(bcp.getQuantity().multiply(bo.getQuantity())); //产品数量乘BOM标准物料的数量
						bcpurch.setAmount(bcpurch.getPrice().multiply(bcpurch.getQuantity()));
						bcpurch.setRemarks(bcp.getRemarks());				
						bcpurch.setCreateTime(new Date());
						bcpurch.setOperator(operator);
						bcplist.add(bcpurch);
					}
				}
				else {
					BmeContPurch bcpurch  = new BmeContPurch();
					bcpurch.setId(IDHelper.genStrID(20));
					bcpurch.setBmeContract(bcp.getBmeContract());
					bcpurch.setContName(bcp.getBmeContract().getName());
					bcpurch.setBmeMaterial(bcp.getBmeMaterial());
					bcpurch.setContName(bcp.getContName());
					bcpurch.setSupplierId(bcp.getSupplierId());
					
					bcpurch.setPrice(bcp.getPrice());
					bcpurch.setQuantity(bcp.getQuantity());
					bcpurch.setAmount(bcp.getAmount());
					
					bcpurch.setRemarks(bcp.getRemarks());				
					bcpurch.setCreateTime(new Date());
					bcpurch.setOperator(operator);
					voppm.add(bcpurch);
				}
			}
			
			//以上一步生成的BOM物料相关的BmeContPurch列表为基础，进行合并或者插入操作
			//BOM的合并或插入：MID相同的合并，没有MID则插入
			boolean find=false;
			for(BmeContPurch bpurch:bcplist) { 
				find=false;
				for(BmeContPurch bcp:voppm) { //已有的BmeContPurch
					if(bpurch.getBmeMaterial().getId().equals(bcp.getBmeMaterial().getId()) ) { //合并
						bcp.setQuantity(bpurch.getQuantity().add(bcp.getQuantity()));	//数量相加
						bcp.setAmount(bcp.getPrice().multiply(bcp.getQuantity()));		//金额计算
						find=true;
					}
				}
				if(!find){ //插入
					//db.insert(bpurch);
					voppm.add(bpurch);
				}
			}
			//db.getEm().clear();
			//清除合同下已有清单数据
			sql = "delete from BmeContPurch o where o.bmeContract.id=?1";
			db.beginTransaction();
			db.createQuery(sql).setParameter(1, bmeContractId).executeUpdate();//delete 的记录数
			for(BmeContPurch bcp:voppm) {
				db.insert(bcp);
			}
			db.commitTransaction();
			//AppInitInfo.showMessage("生成采购清单", "处理成功");
			//io.setBmeContPurches(voppm);  //必须设置：不然查询时当前记录不会显示出来
			
		}catch(Exception ex) {
			//AppInitInfo.showMessage("生成采购清单", "处理失败");
			log.error(ex.getLocalizedMessage());
			voppm = new ArrayList<BmeContPurch>();
			try{
				db.rollbackTransaction();
				}catch(Exception e) {};		
		}
		
	}
	
	//日期查询
	public static void dataQuery() {
		DbAccess db = new DbAccess();
		
		 //sTime...2018-06-26 00:00:00
		 //eTime...2018-06-27 59:59:59
		 //beginTime=Tue Jun 26 00:00:00 CST 2018
		 //endTime=Fri Jun 29 11:59:59 CST 2018
		 
		String sTime = "2018-06-26 00:00:00";
		String eTime = "2018-06-27 23:59:59";
	
		
		Date beginTime = DateHelper.strToDate(sTime, DateHelper.DF_DEFAULT);
		Date endTime  = DateHelper.strToDate(eTime, DateHelper.DF_DEFAULT);
		
		System.out.println("beginTime="+beginTime);
		System.out.println("endTime="+endTime);
		
		String sql = "SELECT m FROM BmePurchOrder m WHERE m.orderDate BETWEEN ?1 AND ?2 ";
		System.out.println(db.findBySql(sql.toString(),new Object[]{beginTime,endTime}).size());
	}

	public static Collection<SysDictitem> getDictcodeList(List<SysDictitem> list,String dictcode) {			
		Collection<SysDictitem>  filterCollection = 
			       Collections2.filter(list, new Predicate<SysDictitem>(){ 
			   @Override 
			   public boolean apply(SysDictitem input) { 
			       return dictcode.equalsIgnoreCase(input.getDictcode()); //返回符合条件的集合
			}});
		return filterCollection;	
	}
	
	public static void AppInitInfo() {
		  
		AppInitInfo.getDropdownList("Msort","NULL");  //SysDictitems数据字典转换为下拉数据
		AppInitInfo.getDropdownList("BmeMaterial","id","mdesc");//实体BmeMaterial中数据id，mdesc直接转化成下拉数据
		AppInitInfo.getDropdownMap("BmeCustomer","id","name");//实体BmeCustomer中数据id，name直接转化成下拉数据
		
	}
	
}
